import com.jcraft.jsch.*;

import static org.fusesource.jansi.Ansi.Color.GREEN;
import static org.fusesource.jansi.Ansi.Color.RED;
import static org.fusesource.jansi.Ansi.ansi;
import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {

    String host;
    String username;
    String password;
    String localDir;
    //线程池
    static int numThreads = 5;
    static ExecutorService executorService = Executors.newFixedThreadPool(numThreads);

    public Test(String host, String username, String password, String localFilePath) {
        this.host = host;
        this.username = username;
        this.password = password;
        this.localDir = localFilePath;
    }

    public void serverSFTPConnection() {
//        String host = "8.130.104.107";
//        String username = "root";
//        String password = "G180813y";
//        String localFilePath = "D:\\ftprest";
        int port = 22; // SFTP默认端口
        String remoteDir = "/www/wwwroot";
        JSch jsch = new JSch();
        try {
            Session session = jsch.getSession(username, host, port);
            session.setConfig("StrictHostKeyChecking", "no"); // 跳过主机密钥检查
            session.setPassword(password);
            session.connect();

            ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();

            SftpATTRS attrs = channelSftp.lstat(remoteDir);
            // 获取文件的修改时间
            long modifyTime = attrs.getMTime() * 1000L;
            // 将秒转换为毫秒
            File file = new File(localDir);
            long lastModified = file.lastModified();
            //如果服务器的修改时间早于本地的修改时间，再发送一遍（覆盖掉之前的）
            System.out.println(lastModified);
            System.out.println(modifyTime);
            if (modifyTime > lastModified) {
                System.out.println("修改了");
                try {
                    uploadDirectory(channelSftp, localDir, remoteDir);
                } catch (SftpException e1) {
                    System.out.print(ansi().fg(RED).a("文件同步失败！\t").reset());
                }
            }

            channelSftp.disconnect();
            session.disconnect();

//            AnsiConsole.systemInstall();
            System.out.print(ansi().fg(GREEN).a("文件同步完成！\t").reset());

        } catch (Exception e) {
            System.out.print(ansi().fg(RED).a("文件同步失败！\t").reset());
        }
    }

    private static void uploadDirectory(ChannelSftp channelSftp, String localDir, String remoteDir) throws SftpException {
        File localFile = new File(localDir);
        if (localFile.isDirectory()) {
            // 在远程服务器上创建相应的目录
            try {
                System.out.println(remoteDir + "/" + localFile.getName());
                channelSftp.mkdir(remoteDir + "/" + localFile.getName());
            } catch (SftpException e) {
                System.out.print("1");
                e.printStackTrace();
            }

            // 进入新创建的远程目录
            try {
                channelSftp.cd(remoteDir + "/" + localFile.getName());
            } catch (SftpException e) {
                System.out.println("2");
            }

            // 遍历本地文件夹中的所有文件和子文件夹
            for (File file : localFile.listFiles()) {
                if (file.isFile()) {
                    // 上传文件
                    channelSftp.put(file.getAbsolutePath(), file.getName());
//                    executorService.submit(() -> {
//                        try {
//                            channelSftp.put(file.getAbsolutePath(), file.getName());
//                        } catch (SftpException e) {
//                            e.printStackTrace();
//                        }
//                    });
                } else if (file.isDirectory()) {
                    // 递归上传子文件夹
                    uploadDirectory(channelSftp, file.getAbsolutePath(), remoteDir + "/" + localFile.getName());
//                    executorService.submit(() -> {
//                        try {
//                            uploadDirectory(channelSftp, file.getAbsolutePath(), remoteDir + "/" + localFile.getName());
//                        } catch (SftpException e) {
//                            e.printStackTrace();
//                        }
//                    });
                }
            }
        }
    }

}
